package org.celery.common.utils;

import org.celery.core.secure.MemberAuthInfo;
import org.celery.modules.member.entity.Member;
import org.springblade.core.launch.constant.TokenConstant;
import org.springblade.core.secure.TokenInfo;
import org.springblade.core.secure.utils.SecureUtil;
import org.springblade.core.tool.utils.Func;

import java.util.HashMap;
import java.util.Map;

/**
 * 会员token工具类
 *
 * @author Celery
 * @since 2021-11-26
 */
public class MemberTokenUtil {

    /**
     * 创建认证token
     *
     * @param member 会员信息
     * @return token
     */
    public static MemberAuthInfo createAuthInfo(Member member) {
        //设置jwt参数
        Map<String, String> param = new HashMap<>(16);
        param.put(TokenConstant.TOKEN_TYPE, TokenConstant.ACCESS_TOKEN);
        param.put(TokenConstant.USER_ID, Func.toStr(member.getId()));
        param.put(TokenConstant.USER_NAME, member.getNickname());

        TokenInfo accessToken = SecureUtil.createJWT(param, "audience", "issuser", TokenConstant.ACCESS_TOKEN);
        MemberAuthInfo authInfo = new MemberAuthInfo();
        authInfo.setUserId(member.getId());
        authInfo.setNickname(member.getNickname());
        authInfo.setWxMaOpenId(member.getWxMaOpenId());
        authInfo.setAvatar(member.getAvatar());
        authInfo.setBirthday(member.getBirthday());
        authInfo.setSex(member.getSex());
        authInfo.setPhone(member.getPhone());
        authInfo.setAccessToken(accessToken.getToken());
        authInfo.setExpiresIn(accessToken.getExpire());
        authInfo.setRefreshToken(createRefreshToken(member).getToken());
        authInfo.setTokenType(TokenConstant.BEARER);
        authInfo.setLicense(TokenConstant.LICENSE_NAME);

        return authInfo;
    }

    /**
     * 创建refreshToken
     *
     * @param member 会员信息
     * @return refreshToken
     */
    private static TokenInfo createRefreshToken(Member member) {
        Map<String, String> param = new HashMap<>(16);
        param.put(TokenConstant.TOKEN_TYPE, TokenConstant.REFRESH_TOKEN);
        param.put(TokenConstant.USER_ID, Func.toStr(member.getId()));
        return SecureUtil.createJWT(param, "audience", "issuser", TokenConstant.REFRESH_TOKEN);
    }
}
